from http import cookies

from django import forms
# 加密密码和验证密码
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import check_password, make_password
# HttpResponseRedirect  HttpResposne
from django.http import HttpResponseRedirect, HttpResponse
# render
from django.shortcuts import render

# Create your views here.
# 表单的 api
from .models import user


class UserForm(forms.Form):
    username = forms.CharField(label='用户名', max_length=10)
    # 想输入密码文
    password = forms.CharField(label='密码', widget=forms.PasswordInput())


# 处理登录的方法
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    if request.method == 'POST':
        data = UserForm(request.POST)
        # 方法函数is_valid()的作用检查seld.errors是否都正确，例如长度，空值，类型等
        if data.is_valid():
            # 获取到表单提交的值
            username = data.cleaned_data['username']
            password = data.cleaned_data['password']
            print(username, password)

    #         # authenticate 函数会自动帮你验证是否匹配
    #         use = authenticate(request, username=username, password=password)
    #         print(use)
    #         if use:
    #             return HttpResponse("登陆成功")
    #         else:
    #             return HttpResponse("用户或密码错误")
    #     else:
    #         print(data.cleaned_data)
    #         print(data.errors)
    #         return render("严重失败,错误愿意如下", request, "login.html", {"data": data})
    #
    # data = UserForm()
    # return render(request, 'login.html', {"data": data})


            # 把表单中取到的值和数据库里做对比
            use = user.objects.get(u_name=username)
            check = check_password(password, use.u_password)


            # 判断对比是否成功
            if use and check:
                ticket = 'asdsadjs'
                response = HttpResponseRedirect('/login/index')
                # 创建cookie
                response.set_cookie('ticket', ticket, 3600)
                # 把cookie的值保存到数据库中
                use.u_ticket = ticket
                use.save()
                # 把cookie返回到浏览器中
                return response
            else:
                return HttpResponseRedirect('/login/day_logins/')


#  注册相应的方法
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    if request.method == 'POST':
        data = UserForm(request.POST)
        if data.is_valid():
            username = data.cleaned_data['username']
            password = data.cleaned_data['password']
            # 对密码进行加密处理，保存到数据中
            # password = password
            password = make_password(password)
            try:
                # 判断用户是否已经注册
                registjudge = user.objects.filter(u_name=username).get()
                return HttpResponse('用户已经存在')
            except:
                # 把注册的数据保存到数据库中
                registadd = user.objects.create(
                    u_name=username,
                    u_password=password
                )
                return HttpResponseRedirect('/login/day_logins/')


def logout(request):  # 退出登录方法
    if request.method == 'GET':
        response = HttpResponseRedirect('/login/day_logins/')
        response.delete_cookie('ticket')
        return response


# 登录成功后进入主页的方法
def index(request):
    if request.method == 'GET':
        response = HttpResponseRedirect('/login/day_logins/')
        response.delete_cookie('ticket')
        return response


# 登陆成功后进入主页的方法
def index(request):
    if request.method == 'GET':
        # 获取到浏览器中的cookie
        cookie = request.COOKIES.get('ticket')
        # 判断cookie 是否存在
        if not cookies:
            return render(request, 'login.html')
        # 把cookie里的值和数据库里的相比较，对比成功进入主页，否则返回登录界面
        if user.objects.filter(u_ticket=cookie).exists():
            return render(request, 'index.html')
        else:
            return render(request, 'login.html')
